package com.eagle.view.fragment.live;

import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eagle.R;
import com.eagle.support.common.CameraDataCallback;
import com.eagle.support.helper.CallHelper;
import com.eagle.support.utils.Utility;
import com.eagle.support.utils.Utils;
import com.eagle.support.utils.YuvRender;
import com.eagle.view.activity.LiveShowActivity;
import com.eagle.view.widget.CameraTextureView;
import com.kinstalk.voip.jni.NVDataRender;
import com.kinstalk.voip.jni.VideoRotation;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.PropertyValuesHolder;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/7.
 */
@EFragment(R.layout.fragment_live_show_audience)
public class FragmentAudienceLiveShow extends BaseFragment implements CameraDataCallback {

    private static final String TAG = "cim";

    @ViewById(R.id.tv_live)
    protected CameraTextureView mCameraTextureView;

    @ViewById(R.id.layout_preview)
    protected RelativeLayout mLayoutPreview;

    @ViewById(R.id.liveSurfaceViewRemoteVideo)
    protected GLSurfaceView mSurfaceViewRemoteVideo;

    @ViewById(R.id.tv_download)
    protected TextView mTvDownload;

    @ViewById(R.id.tv_upload)
    protected TextView mTvUpload;

    private byte[] newData;

    private int mPhoneOrientation = 3;

    private LiveShowActivity mActivity;

    private CallHelper mLiveShowHelper;

    private YuvRender mRemoteRender;

    private NVDataRender mRemoteDataRender = new NVDataRender();

    /**
     * 是否开始连麦
     */
    private boolean mConnected;

    @AfterViews
    void initView() {
        mActivity = (LiveShowActivity) getActivity();
        newData = new byte[320 * 240 * 3 / 2];
        mLiveShowHelper = mActivity.getCallHelper();
        mCameraTextureView.setDataCallback(this);
        onHandlerCamera(true);

        this.mRemoteRender = new YuvRender();
        this.mRemoteRender.setDataRender(mRemoteDataRender);
        mSurfaceViewRemoteVideo.setEGLContextClientVersion(2);
        mSurfaceViewRemoteVideo.setRenderer(mRemoteRender);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            hideCamera(false);
        }
    }

    @Override
    public void onCameraData(byte[] data, Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        if (mLiveShowHelper.getLoader().getCurrentCallInfo() != null && !isHidden()) {
            // 如果是前置摄像头， 需要将图像上下翻转
            int orientation = mPhoneOrientation;
            if (mCameraTextureView.getCameraId() == Camera.CameraInfo.CAMERA_FACING_FRONT && orientation % 2 == 1) {
                VideoRotation.rotationProcess(data, newData, size.width, size.height, orientation);
            }

            if (mConnected)
                mLiveShowHelper.getLoader().getCurrentCallInfo().sendDataOnMainVideoChannel(EngineSdkVideoPixelFormat.ES_PIXEL_FORMAT_NV21, size.width, size.height, (char) orientation, newData);
        }
    }

    public void onMainVideoDataInCall(long pointer, int width, int height, char rotation) {
        if (mRemoteDataRender != null && mRemoteRender != null && mSurfaceViewRemoteVideo != null) {
            mRemoteDataRender.CopytoRenderBuffer(pointer, width, height);
            if (!mRemoteRender.IsSetuped())
                mRemoteRender.SetupRender(width, height);
            mRemoteRender.updateFrameInfo(width, height, rotation);
            if (mSurfaceViewRemoteVideo != null)
                mSurfaceViewRemoteVideo.requestRender();
        }
    }

    public void onHandlerCamera(boolean open) {
        if (open) {
            mCameraTextureView.setPreviewAreaSize(Utils.dip2px(120), Utils.dip2px(160));
        } else {
            hideCamera(true);
            mCameraTextureView.setDataCallback(null);
            mCameraTextureView.destroyCamera();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                int newOrientation = Utility.getDirection((int) event.values[0], (int) event.values[1], (int) event.values[2]);
                if (mPhoneOrientation != newOrientation) {
                    mPhoneOrientation = newOrientation;
                }
                break;
            case Sensor.TYPE_PROXIMITY:
                // onProximityChanged(event);
                break;
            default:
                break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    public void switchCamera() {
        mCameraTextureView.changeCamera();
        mLayoutPreview.postDelayed(() -> ObjectAnimator.ofFloat(mLayoutPreview, "rotationY", 0.0F, 180.0F).setDuration(300).start(), 150);
    }

    public void receiverSpeed(String rx, String tx) {
        mTvDownload.setText(rx);
        mTvUpload.setText(tx);
    }

    public void setConnected(boolean mConnected) {
        this.mConnected = mConnected;
    }

    public void hideCamera(boolean hide) {
        if (hide) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(mLayoutPreview, "alpha", 1.0f, 0.0f);
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mLayoutPreview.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animator.setDuration(300).start();
        } else {
            mLayoutPreview.setVisibility(View.VISIBLE);
            PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0.0f, 1.0f);
            PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.0f, 1.0f);
            PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.0f, 1.0f);
            PropertyValuesHolder translationX = PropertyValuesHolder.ofFloat("translationX", Utils.dip2px(142), 0);
            ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(mLayoutPreview, alpha, scaleX, scaleY, translationX);
            animator.setInterpolator(new OvershootInterpolator());
            animator.setDuration(300).start();
        }
    }
}
